import {defineStore} from "pinia";
import {LoginResp, LoginUser} from "@/api/auth/types.ts";
import {isEmpty, useStorage} from "@/utils";
import {authApi} from "@/api/auth";
import type {SysMenu} from "@/api/menu/types.ts";
import {menuApi} from "@/api";
import {resetRouter} from "@/router";


interface State {
    accessToken: string
    refreshToken: string
    tokenType: string
    loginUser: LoginUser | null
    hasGetRoutes: boolean
    menus: SysMenu[]
}

enum LocalKey {
    ACCESS_TOKEN = 'accessToken',
    REFRESH_TOKEN = 'refreshToken',
    TOKEN_TYPE = 'tokenType',
    LOGIN_USER = 'loginUser',
    HAS_GET_ROUTES = 'hasGetRoutes',
    MENUS = 'menus'
}

const storage = useStorage('auth-store');
export const useAuthStore = defineStore('auth-store', {
    persist: false,
    state: (): State => {
        return {
            accessToken: storage.getOrDefault(LocalKey.ACCESS_TOKEN, ''),
            refreshToken: storage.getOrDefault(LocalKey.REFRESH_TOKEN, ''),
            tokenType: storage.getOrDefault(LocalKey.TOKEN_TYPE, ''),
            loginUser: storage.getOrDefault(LocalKey.LOGIN_USER, null),
            hasGetRoutes: storage.getOrDefault(LocalKey.HAS_GET_ROUTES, false),
            menus: storage.getOrDefault(LocalKey.MENUS, [])
        }
    },
    actions: {
        initToken(resp: LoginResp) {
            this.accessToken = storage.set(LocalKey.ACCESS_TOKEN, resp.access_token, resp.expires_in * 1000)
            this.refreshToken = storage.set(LocalKey.REFRESH_TOKEN, resp.refresh_token, resp.expires_in * 2000)
            this.tokenType = storage.set(LocalKey.TOKEN_TYPE, resp.token_type, resp.expires_in * 2000)
        },
        isLogin() {
            return !isEmpty(this.accessToken);
        },
        clearToken() {
            resetRouter()
            this.accessToken = ''
            this.refreshToken = ''
            this.tokenType = ''
            this.hasGetRoutes = false
            this.menus = []
            storage.remove(LocalKey.ACCESS_TOKEN)
            storage.remove(LocalKey.REFRESH_TOKEN)
            storage.remove(LocalKey.TOKEN_TYPE)
            storage.remove(LocalKey.LOGIN_USER)
        },
        initUserInfo() {
            authApi.userInfo().then(res => {
                this.loginUser = storage.set(LocalKey.LOGIN_USER, res.data)
            })
        },
        hasPermission(permissionCode: string | undefined) {
            if (!permissionCode) {
                return true;
            }
            if (this.loginUser) {
                return this.loginUser.authorities.includes(permissionCode);
            }
            return false;
        },
        async getDynamicMenus() {
            if (this.menus.length === 0) {
                const res = await menuApi.treeByUser();
                this.menus = res.data
            }
            return this.menus
        }
    }
})
